import {Button, Form, Input, message} from 'antd';
import {ValidateErrorEntity} from "rc-field-form/lib/interface";
import {LockOutlined, UserOutlined} from "@ant-design/icons";
import {LoginFieldType} from "../../types/user.ts";
import {useAuth} from "../../context/auth-context.tsx";
import {ReactNode} from "react";

export const RegisterForm = ({children, handleSwitchLogin}: { children: ReactNode, handleSwitchLogin: () => void }) => {
    const {register} = useAuth()

    const onFinish = async (loginForm: LoginFieldType) => {
        try {
            await register(loginForm)
            message.success('注册成功，请登录')
            handleSwitchLogin()
        } catch (e) {
            console.log(e)
        }
    }

    const onFinishFailed = (errorInfo: ValidateErrorEntity<LoginFieldType>) => {
        console.log('Failed:', errorInfo);
    };
    return <Form
        name="registerForm"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
    >
        <Form.Item<LoginFieldType>
            name="username"
            rules={[{required: true, message: '请输入用户名!'}]}
        >
            <Input
                prefix={<UserOutlined className="site-form-item-icon"/>}
                placeholder="用户名"
                key={'username'}
            />
        </Form.Item>

        <Form.Item<LoginFieldType>
            name="password"
            rules={[{required: true, message: '请输入密码!'}]}
        >
            <Input.Password
                type="password"
                prefix={<LockOutlined className="site-form-item-icon"/>}
                placeholder="密码"
                key={'password'}
            />
        </Form.Item>
        <Form.Item>
            <Button block type="primary" htmlType="submit">
                注册
            </Button>
        </Form.Item>
        <Form.Item>
            {children}
        </Form.Item>
    </Form>
}